import Vue from 'vue'
import Vuex from 'vuex'
import cache from '@/utils/cache'
import constants from '@/config/constants'
import sysUserApi from '@/api/sysUserApi'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: cache.localGet(constants.CACHE.TOKEN),  //token信息
    user: cache.sessionGet(constants.CACHE.USER_INFO),  //用户信息
		userMenuList: cache.sessionGet(constants.CACHE.USER_MENU_LIST),  //菜单列表
		firstMenuIndex: cache.sessionGet(constants.CACHE.FIRST_MENU_INDEX) ? cache.sessionGet(constants.CACHE.FIRST_MENU_INDEX) : 0  //选中的第一层菜单索引
  },
  mutations: {
    /* 设置token */
    setToken (state, data) {
      state.token = data;
      cache.localSet(constants.CACHE.TOKEN, data);
      this.commit(constants.STORE.UPDATE_USER);
			this.commit(constants.STORE.SET_USER_MENU_LIST);
			this.commit(constants.STORE.SET_FIRST_MENU_INDEX, 0);
    },
    /* 更新用户信息 */
    async updateUser (state){
      if(state.token){
        const result = await sysUserApi.sysUserDetail(state.token.id);
        state.user = result.data;
        cache.sessionSet(constants.CACHE.USER_INFO, result.data);
      }
    },
		/* 设置菜单列表 */
		async setUserMenuList (state){
			if(state.token){
				const result = await sysUserApi.sysUserMenuTree(state.token.id);
				state.userMenuList = result.data;
				cache.sessionSet(constants.CACHE.USER_MENU_LIST, result.data);
			}
		},
    clearUser (state) {
      //移除token
      state.token = null;
      cache.localSet(constants.CACHE.TOKEN, null);
      //移除用户信息
      state.user = null;
      cache.sessionSet(constants.CACHE.USER_INFO, null);
			//移除菜单信息
			state.user = null;
			cache.sessionSet(constants.CACHE.USER_MENU_LIST, null);
		},
		/* 设置选中的第一层菜单索引 */
		setFirstMenuIndex(state, data){
			state.firstMenuIndex = data;
			cache.sessionSet(constants.CACHE.FIRST_MENU_INDEX, data);
		}
  },
  actions: {
  },
  modules: {
  }
})
